import { _decorator, Component, Node, director, Widget, sys, Prefab, instantiate, tween, Vec3 } from 'cc';
import { Config } from './Config';
import { AudioManager } from './AudioManager';
import { utils } from './utils';
import { ndSidebar } from './ndSidebar';
import { msgToast } from './msgToast';
import { SDKManager } from './SDKManager';
import { ReactiveAutoSave } from './Tool/ReactiveAutoSave';
const { ccclass, property } = _decorator;

@ccclass('gameMain')

export class gameMain extends Component {

    // @property(Sprite)
    // public UImg: Sprite = null!

    // @property(Label)
    // public UName: Label = null!

    @property(AudioManager)
    audioManager: AudioManager = null!;

    @property({ type: ndSidebar })
    public ndSidebar: ndSidebar = null!

    @property({ type: Node })
    public uiBackground: Node = null!;
    // 容器设置按钮
    @property({ type: Node })
    public LTop: Node = null!;

    @property({ type: Node })
    public btnGetAward = null!;

    @property({ type: Node })
    public btnGotoSidebar = null!;

    @property({ type: Node })
    public btnSidebar = null!;
    
    @property({ type: Node })
    public logo: Node = null!;


    @property({ displayName: '微信插屏广告' })
    private wx_intersitialAdUnitId: string = '';
    @property({ displayName: '微信视频广告' })
    private wx_rewardedVideoAdUnitId: string = '';
    @property({ displayName: '微信Banner广告', tooltip: '请使用原生模板广告' })
    private wx_bannerAdAdUnitId: string = '';
    @property({ displayName: '微信原生模板广告', tooltip: '仅支持微信平台' })
    private customAdUnitId: string = '';


    @property({ displayName: '抖音插屏广告' })
    private dy_intersitialAdUnitId: string = '';
    //激励视频广告
    @property({ displayName: '抖音视频广告' })
    private dy_rewardedVideoAdUnitId: string = '';
    //横幅广告
    @property({ displayName: '抖音Banner广告', tooltip: '抖音基本没有Banner广告' })
    private dy_bannerAdAdUnitId: string = '';

    //抖音侧边栏-默认不是
    private isFromSidebar = false;

    start() {
        tween(this.logo)
            .to(1, { scale: new Vec3(1.1, 1.1, 1.1) })
            .to(1, { scale: new Vec3(1, 1, 1) })
            .union()
            .repeatForever()
            .start()
        //从服务器获取用户openid----unionid
        let self = this;
        if (self.uiBackground) self.uiBackground.setScale(1, Config.heightScaling);
        // console.log("平台：" + SDKManager.platform() + " 平台")
        if (sys.platform == sys.Platform.WECHAT_GAME) {
            Config.intersitialAdUnitId = this.wx_intersitialAdUnitId;
            Config.rewardedVideoAdUnitId = this.wx_rewardedVideoAdUnitId;
            Config.bannerAdAdUnitId = this.wx_bannerAdAdUnitId;
            Config.customAdUnitId = this.customAdUnitId;
        } else if (sys.platform == sys.Platform.BYTEDANCE_MINI_GAME) {
            Config.intersitialAdUnitId = this.dy_intersitialAdUnitId;
            Config.rewardedVideoAdUnitId = this.dy_rewardedVideoAdUnitId;
            Config.bannerAdAdUnitId = this.dy_bannerAdAdUnitId;
        }
        let rect = SDKManager.getMenuButtonRect();
        if (rect) {
            let widget = self.LTop.getComponent(Widget)
            widget.top = rect.top
        }

        //设置
        SDKManager.setting();
        //显示插屏广告
        SDKManager.showInterstitialAd(2);
        //获取胶囊的rect
        if (sys.platform === sys.Platform.WECHAT_GAME) {

            let wx = SDKManager.platform();
            //游戏圈---仅支持微信
            SDKManager.showClubButton();

            //第一次进入页面查询
            if (Config.openid) return;
            wx.login({
                success({ code }) {
                    if (code) {
                        //从服务器获取用户openid----unionid
                        utils.call('get', { type: 'WX_FQHY_OPENID', code, }).then(resa => {
                            let res: any = resa
                            Config.openid = res?.openid as string || ''
                            Config.unionid = res?.unionid as string || ''
                            self.regUser()
                            //self.getUserinfo()
                        }).catch(() => { })
                    }
                }
            })


        } else if (sys.platform === sys.Platform.BYTEDANCE_MINI_GAME) {
            let tt = SDKManager.platform();
            SDKManager.showGridGamePanel();

            tt.onShow((res) => {
                //console.log('tt.onShow-----', res)
                //判断用户是否是从侧边栏进来的
                self.isFromSidebar = (res.launch_from == 'homepage' && res.location == 'sidebar_card')
                if (self.isFromSidebar) {
                    
                    //如果是从侧边栏进来的，显示“领取奖励”按钮，隐藏“去侧边栏”
                    if (self.btnGetAward) self.btnGetAward.active = true
                    if (self.btnGotoSidebar) self.btnGotoSidebar.active = false
                }
                else {
                    //否则反之
                    if (self.btnGetAward) self.btnGetAward.active = false
                    if (self.btnGotoSidebar) self.btnGotoSidebar.active = true
                }
            });

            //判断用户是否支持侧边栏进入功能，有些旧版的抖音没有侧边栏，这种情况就把入口有礼那个按钮给隐藏掉
            tt.checkScene({
                scene: 'sidebar',
                success: () => { 
                    if(ReactiveAutoSave.ins.getData().gift == 1){
                        return self.btnSidebar.active = false
                    }
                    self.btnSidebar.active = true
                 },
                fail: () => { self.btnSidebar.active = false }
            });

            if (Config.openid) return;
            //获取抖音登录用户openid
            tt.login({
                force: true,
                success({ code }) {
                    if (code) {
                        //发起网络请求
                        // console.log(code)
                        // utils.call('get', { type: 'DY_FQHY_OPENID', code, }).then(resa => {
                        //     let res: any = resa
                        //     Config.openid = res?.data?.openid as string || ''
                        //     Config.unionid = res?.data?.unionid as string || ''
                        //     self.regUser()
                        //     //self.getUserinfo()
                        // }).catch(() => { })
                    }
                }
            })

        }
    }


    regUser() {
        utils.call('get', {
            type: 'regUser',
            Id: Config.openid,
            data: {
                unionid: Config.unionid,
                appid: Config.appid,
            }
        }).then(resa => {
            let res: any = resa
            Config.uName = res?.uName || ''
            Config.uImg = res?.uImg || ''
        }).catch(err => {
            //console.log(err)
        })
    }


    //点击入口有礼按钮，显示对话框
    onbtnOpenSideBarDialog() {
        this.ndSidebar.show()
    }

    //去侧边栏按钮的逻辑
    onbtnGotoSidebarClick() {
        SDKManager.navigateToScene();
    }
    //领取奖励的逻辑，自己实现
    onbtnGetAwardClick() {
        ReactiveAutoSave.ins.getData().gift = 1
        this.showToast('活动火爆 奖励已领完！')
    }

    onBtnPlay() {
        this.audioManager.playSound();
        Config.loading = true;
        director.loadScene('gameManager');
        SDKManager.hideClubButton();
        SDKManager.hideGamePanel();

    }

    //showToast
    @property({ type: Prefab })
    public toastPrefab: Prefab = null!;
    /**
     * showToast
     * @param conent 内容
     */
    public showToast(conent: string) {
        let t = instantiate(this.toastPrefab)
        let script = t.getComponent(msgToast);
        script.showToast(conent)
        this.node.addChild(t)
    }


}

